<template>
	<view class="cardBg">
		<!-- 标签页导航 -->
		<view class="tabs" :class="{ loading: !tabDataLoaded }">
			<view v-for="(item,index) in tabsList" :key="index" class="tabItem" @click="changeTabs(index)"
				:class="{ active: tabsCurrent === index }"
				:style="{borderBottom: tabsCurrent === index ? '#73F0EA 8rpx solid' : ''}">
				<view class="size" :style="{
						color: tabsCurrent === index ? '#73F0EA' : '#999999',
						fontWeight: tabsCurrent === index ? '800' : '400'
					}">
					{{item.name}}
				</view>
			</view>
		</view>

		<!-- 内容区域 -->
		<scroll-view scroll-y="true" class="scroll-y">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<view class="loading-card" v-for="n in 3" :key="n" :style="{ animationDelay: (n-1) * 0.2 + 's' }">
					<view class="skeleton-card"></view>
				</view>
			</view>

			<!-- 错误状态 -->
			<view v-else-if="loadError" class="error-container">
				<view class="error-content">
					<u-icon name="wifi-off" size="60" color="#ccc"></u-icon>
					<text class="error-text">加载失败，请重试</text>
					<u-button type="primary" size="medium" @click="retryLoad">重新加载</u-button>
				</view>
			</view>

			<!-- 卡片列表 -->
			<view v-else-if="cardList.length" class="comlum_box">
				<view v-for="(item,index) in cardList" :key="index" class="Item" @click="routeDetail(item,index)"
					:style="{ animationDelay: index * 0.1 + 's' }">
					<!-- 卡片 -->
					<Card :userQuery="item" :iconShow="true" @stopClick="parentHandleStopCard"></Card>
				</view>
			</view>

			<!-- 空状态 -->
			<empty v-else :content="getEmptyText()">
			</empty>
		</scroll-view>
		<!-- 停卡弹窗 -->
		<stopCard :visible.sync="visible" :useStopCard="useStopCard" :stopCardDesc="stopCardDesc" @confirm="confirm">
		</stopCard>
	</view>
</template>

<script>
	import empty from './components/empty.vue'
	import Card from './components/card.vue'
	import stopCard from './components/stopCar.vue'
	import {
		mycardList,
		stopCar,
		startCar
	} from "@/api/user.js"
	export default {
		components: {
			empty,
			Card,
			stopCard
		},
		data() {
			return {
				// 当前筛选表单参数
				form: '',
				// 标签页配置
				tabsList: [{
						name: '全部',
						form: ''
					},
					{
						name: '使用中',
						form: 'effect'
					},
					{
						name: '已过期',
						form: 'past'
					},
					{
						name: '未启用',
						form: 'enabled'
					}
				],
				// 当前选中的标签页索引
				tabsCurrent: 0,
				// 卡片列表数据
				cardList: [],
				// 页面状态管理
				loading: false,
				loadError: false,
				// 标签页数据加载状态
				tabDataLoaded: false,
				useStopCard: '',
				visible: false,
				stopCardDesc: '',
				currentCard: null
			}
		},
		computed: {
			/**
			 * 获取空状态显示文本
			 */
			getEmptyText() {
				const emptyTexts = [
					'暂无会员卡',
					'暂无使用中会员卡',
					'暂无已过期会员卡',
					'暂无未启用会员卡'
				]
				return () => emptyTexts[this.tabsCurrent] || emptyTexts[0]
			}
		},
		onLoad() {
			this.initializePageData()
		},
		onShow() {
			this.getMyCardList()
		},

		methods: {
			/**
			 * 初始化页面数据
			 */
			async initializePageData() {
				try {
					this.loading = true
					this.loadError = false

					// 并行加载标签页数据和卡片列表
					await Promise.all([
						this.getTabData(),
						this.getMyCardList()
					])
				} catch (error) {
					console.error('页面初始化失败:', error)
					this.loadError = true
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			/**
			 * 切换标签页
			 * @param {number} index - 标签页索引
			 */
			changeTabs(index) {
				if (this.tabsCurrent === index || this.loading) return

				this.tabsCurrent = index
				this.form = this.tabsList[index].form
				this.getMyCardList()
			},

			/**
			 * 获取标签页数据（包含数量统计）
			 */
			async getTabData() {
				try {
					const {
						data: res
					} = await mycardList()
					if (res.code === 1) {
						this.tabsList[0].name = `全部(${res.data.all_num || 0})`
						this.tabsList[1].name = `使用中(${res.data.effect_num || 0})`
						this.tabsList[2].name = `已过期(${res.data.past_num || 0})`
						this.tabsList[3].name = `未启用(${res.data.enabled_num || 0})`
						this.tabDataLoaded = true
					} else {
						throw new Error(res.msg || '获取标签页数据失败')
					}
				} catch (error) {
					console.error('获取标签页数据失败:', error)
					uni.showToast({
						title: '获取标签数据失败',
						icon: 'none'
					})
					throw error
				}
			},

			/**
			 * 获取我的卡片列表
			 */
			async getMyCardList() {
				try {
					const {
						data: res
					} = await mycardList({
						form: this.form
					})
					if (res.code === 1) {
						this.cardList = res.data.list || []
						// console.log('this.cardList', this.cardList)
					} else {
						throw new Error(res.msg || '获取卡片列表失败')
					}
				} catch (error) {
					console.error('获取卡片列表失败:', error)
					uni.showToast({
						title: '获取卡片列表失败',
						icon: 'none'
					})
					throw error
				}
			},

			/**
			 * 跳转到卡片详情页
			 * @param {Object} item - 卡片数据
			 * @param {number} index - 卡片索引
			 */
			routeDetail(item, index) {
				if (!item || !item.bag_id) {
					uni.showToast({
						title: '卡片信息异常',
						icon: 'none'
					})
					return
				}

				uni.navigateTo({
					url: `card_deatil?bag_id=${item.bag_id}`
				})
			},

			/**
			 * 重新加载页面数据
			 */
			retryLoad() {
				this.initializePageData()
			},
			parentHandleStopCard(e) {
				// console.log(e)
				if (e.use_stop_card === 'use') {
					return;
				}
				this.useStopCard = e.use_stop_card
				this.stopCardDesc = e.stop_card_desc
				this.currentCard = e;
				this.visible = true
			},
			// 确认停卡
			async confirm() {
				// 基础校验：卡片信息和状态必须存在
				if (!this.currentCard || !this.currentCard.bag_id || !this.useStopCard) {
					uni.showToast({
						title: '卡片信息异常，无法操作',
						icon: 'none'
					});
					this.visible = false;
					return;
				}

				const bagId = this.currentCard.bag_id;
				let apiResult;

				try {
					uni.showLoading({
						title: '操作中...',
						mask: true
					});

					if (this.useStopCard === 'no_use') {

						apiResult = await stopCar({
							bag_id: bagId

						});
					} else if (this.useStopCard === 'using') {

						apiResult = await startCar({
							bag_id: bagId

						});
					} else if (this.useStopCard === 'use') {


						this.visible = false;
						return;
					}


					if (apiResult && apiResult.data.code === 1) {
						const successMsg = this.useStopCard === 'no_use' ? '停卡成功' : '启用卡成功';
						uni.showToast({
							title: successMsg
						});
						this.visible = false;
						this.getMyCardList();
					} else {
						uni.showToast({
							title: apiResult?.data?.msg || '操作失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('接口调用异常:', error);
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #e9e9e9;
		// 全局关闭点击高亮效果
		-webkit-tap-highlight-color: transparent;
		tap-highlight-color: transparent;
	}

	// 全局关闭所有可点击元素的高亮效果
	* {
		-webkit-tap-highlight-color: transparent;
		tap-highlight-color: transparent;
		outline: none;
		-webkit-touch-callout: none;
	}

	.cardBg {
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 100vh;

		.tabs {
			width: 100%;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-around;
			background: #ffffff;
			box-shadow: 0rpx 8rpx 28rpx 0rpx rgba(199, 205, 179, 0.15);
			padding-top: 30rpx;
			position: relative;
			transition: all 0.3s ease;

			&.loading {
				opacity: 0.7;
			}

			.tabItem {
				display: flex;
				flex-direction: column;
				align-items: center;
				height: 60rpx;
				position: relative;
				transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				cursor: pointer;
				// 关闭点击高亮效果
				-webkit-tap-highlight-color: transparent;
				tap-highlight-color: transparent;
				outline: none;
				-webkit-touch-callout: none;
				-webkit-user-select: none;
				user-select: none;

				&.active {
					transform: translateY(-2rpx);
				}

				&:hover {
					transform: translateY(-1rpx);
				}

				// 移除按钮点击时的默认高亮
				&:active {
					background-color: transparent !important;
					box-shadow: none !important;
				}

				.size {
					font-size: 28rpx;
					letter-spacing: 0.62rpx;
					font-family: PingFang SC, PingFang SC-Heavy;
					transition: all 0.3s ease;
				}
			}
		}

		.scroll-y {
			width: 100%;
			// height: 100%;
			flex: 1;
			overflow-y: auto;

			.comlum_box {
				// height: 100%;
				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 20rpx 0;

				.Item {
					width: 100%;
					opacity: 0;
					transform: translateY(30rpx);
					animation: fadeInUp 0.6s ease forwards;
					margin-bottom: 20rpx;
					transition: transform 0.3s ease;
					// 关闭点击高亮效果
					-webkit-tap-highlight-color: transparent;
					tap-highlight-color: transparent;
					outline: none;
					-webkit-touch-callout: none;
					-webkit-user-select: none;
					user-select: none;
					flex: 1;

					&:hover {
						transform: translateY(-5rpx);
					}

					&:active {
						transform: scale(0.98);
						background-color: transparent !important;
						box-shadow: none !important;
					}
				}
			}

			// 加载状态样式
			.loading-container {
				width: 100%;
				padding: 40rpx 32rpx;

				.loading-card {
					width: 100%;
					height: 200rpx;
					margin-bottom: 30rpx;
					opacity: 0;
					animation: fadeInUp 0.6s ease forwards;

					.skeleton-card {
						width: 100%;
						height: 100%;
						background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
						background-size: 200% 100%;
						animation: shimmer 1.5s infinite;
						border-radius: 24rpx;
					}
				}
			}

			// 错误状态样式
			.error-container {
				display: flex;
				justify-content: center;
				align-items: center;
				height: 60vh;
				padding: 40rpx;

				.error-content {
					display: flex;
					flex-direction: column;
					align-items: center;
					gap: 30rpx;

					.error-text {
						font-size: 28rpx;
						color: #666;
						margin: 20rpx 0;
					}
				}
			}
		}
	}

	// 动画效果
	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(40rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	@keyframes shimmer {
		0% {
			background-position: -200% 0;
		}

		100% {
			background-position: 200% 0;
		}
	}
</style>